import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Button,
  Space,
  Input,
  Row,
  Col,
  Tabs,
  Modal,
  Form,
  DatePicker,
  Select,
  Checkbox,
  Table,
  InputNumber,
  message,
  Badge,
} from 'antd';
import { PlusOutlined, CloseOutlined, ExclamationCircleOutlined, SyncOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import moment from 'moment';
import CateComp from '@/components/CategoryComponent';
import PartSelect from '@/components/PartSelect';
import SoSelect from '@/components/SoSelect';
import DocHelper from '@/components/DocHelper';
import request from '@/utils/request';

const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = '/api/services/app/OrderHed/';
const apiURLDtl = '/api/services/app/OrderDtl/';
const apiURLRel = '/api/services/app/OrderRel/';
const apiURLCust = '/api/services/app/Customers/';
class ViewPage extends React.Component<any, any> {
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      data: { orderNum: 0 },
      orderDtl: { orderNum: 0, orderLine: 0 },
      orderRel: { orderNum: 0, orderLine: 0, orderRelNum: 0 },
      loading: false,
      visible: false,
      dataSource: [],
      optionCust: [],
      defTab: '1',
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    this.fetchCust();
  }
  onFinishFailed = (errorInfo: any) => {
    let orderErr = 0;
    let orderDtlErr = 0;
    let orderRelErr = 0;
    errorInfo.errorFields.forEach((element: any) => {
      if (element.name[0] == 'orderDtl') {
        orderDtlErr++;
      }
      else if (element.name[0] == 'orderRel') {
        orderRelErr++;
      }
      else if (element.name[0] == 'order') {
        orderErr++;
      }
      this.setState({ orderErr, orderDtlErr, orderRelErr })
    });
  };
  onFinish = (values: { order: any; orderDtl: any; orderRel: any }) => {
    var orderHed = values.order;
    var orderDtl = values.orderDtl;
    var orderRel = values.orderRel;
    try {
      orderHed.requestDate = orderHed?.requestDate.format('YYYY-MM-DD');
      orderHed.orderDate = orderHed?.orderDate.format('YYYY-MM-DD');

      if (orderDtl) {
        orderDtl.requestDate = orderDtl?.requestDate.format('YYYY-MM-DD');
        if (orderDtl.qsDate)
          orderDtl.qsDate = orderDtl?.qsDate.format('YYYY-MM-DD');
        if (orderDtl.warrantyDate)
          orderDtl.warrantyDate = orderDtl?.warrantyDate.format('YYYY-MM-DD');
      }
      if (orderRel) {
        orderRel.requestDate = orderRel?.requestDate.format('YYYY-MM-DD');
      }
      request(apiURL + 'Modify', {
        method: 'POST',
        data: orderHed,
      }).then((response) => {
        if (response) {
          if (response.success) {
            message.success('保存成功！');
          } else {
            message.error(response.error.message);
          }
          this.setState({ loading: false });
        }
      });
      if (orderDtl && orderDtl.id) {
        orderDtl.orderNum = orderHed.orderNum;
        request(apiURLDtl + 'Modify', {
          method: 'POST',
          data: [orderDtl],
        }).then((response) => {
          if (response) {
            if (response.success) {
              message.success('分录保存成功！');
            } else {
              message.error(response.error.message);
            }
            this.setState({ loading: false });
          }
        });
      }
      if (orderRel && orderRel.id) {
        orderRel.orderNum = orderHed.orderNum;
        orderRel.orderLine = orderDtl.orderLine;
        request(apiURLRel + 'Modify', {
          method: 'POST',
          data: [orderRel],
        }).then((response) => {
          if (response) {
            if (response.success) {
              message.success('发货行保存成功！');
            } else {
              message.error(response.error.message);
            }
            this.setState({ loading: false });
          }
        });
      }
      this.setState({ orderErr: 0, orderDtlErr: 0, orderRelErr: 0 })
    } catch (error) {
      message.error('发生错误，请联系管理员');
    }
  };
  fetchCust = () => {
    this.setState({ loading: true });
    request(apiURLCust + 'GetAll', {
      method: 'GET',
      params: { SkipCount: 0, MaxResultCount: 10000 },
    }).then((response) => {
      if (response) {
        if (response.success) {
          var items = response.result?.items;
          this.setState({ optionCust: items });
        } else {
          message.error(response.error?.message);
        }
      }
      this.setState({ loading: false });
    });
  };
  newObj = () => {
    const { currentUser } = this.props;
    var value = {
      entryPerson: currentUser.userName,
    };
    this.formRef.current.resetFields();
    request(apiURL + 'New', {
      method: 'POST',
      data: value,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success('新建订单成功！');
          var order = response.result.data;
          this.setState({ data: order });
          this.formRef.current.setFieldsValue({ order });
        } else {
          message.error(response.error.message);
        }
        this.setState({ loading: false });
      }
    });
  };
  newDtl = () => {
    const { data } = this.state;
    if (data.orderNum == 0) {
      message.warning('请先创建销售订单');
      return;
    }
    var value = {
      orderNum: data.orderNum,
      partNum: '',
      lineDesc: '',
      orderQty: 1
    };

    request(apiURLDtl + 'New', {
      method: 'POST',
      data: value,
    }).then((response) => {
      if (response) {
        this.setState({ loading: true });
        if (response.success) {
          var data = response.result.data;
          this.formRef.current.setFieldsValue({ orderDtl: data });
          this.setState({ defTab: '2', orderDtl: data });
        } else {
          message.error(response.error.message);
        }
        this.setState({ loading: false });
      }
    });
  };
  newRel = () => {
    const { orderDtl } = this.state;
    if (orderDtl.orderNum == 0 || orderDtl.orderLine == 0) {
      message.warning('请先创建销售订单分录');
      return;
    }
    var value = {
      orderNum: orderDtl.orderNum,
      orderLine: orderDtl.orderLine,
    };
    request(apiURLRel + 'New', {
      method: 'POST',
      data: value,
    }).then((response) => {
      if (response) {
        this.setState({ loading: true });
        if (response.success) {
          var data = response.result.data;
          this.formRef.current.setFieldsValue({ orderRel: data });
          this.setState({ defTab: '3', orderRel: data });
        }
        this.setState({ loading: false });
      }
    });
  };
  delObj = () => {
    const { data } = this.state;
    let _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.props
          .dispatch({
            type: 'Abp/delete',
            payload: { id: data.id },
            control: 'OrderHed',
          })
          .then(() => {
            _this.formRef.current.resetFields();
            _this.setState({ data: { orderNum: 0 } });
          });
      },
    });
  };
  delDtl = () => {
    const { selectedRowKeys, orderDtls } = this.state;
    let _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.props
          .dispatch({
            type: 'Abp/delPatch',
            payload: selectedRowKeys,
            control: 'OrderDtl',
          })
          .then(() => {
            let lists = orderDtls.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0);
            _this.setState({ orderDtls: lists });
          });
      },
    });
  };
  delRel = () => {
    const { selectedRowKeys2, orderRels } = this.state;
    let _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.props
          .dispatch({
            type: 'Abp/delPatch',
            payload: selectedRowKeys2,
            control: 'OrderRel',
          })
          .then(() => {
            let lists = orderRels.filter((o: any) => selectedRowKeys2.indexOf(o.id) < 0);
            _this.setState({ orderRels: lists });
          });
      },
    });
  };
  getObj = (e: any) => {
    if (e.orderNum) {
      this.formRef.current.resetFields();
      this.setState({ loading: true });
      request(apiURL + 'GetByNum', {
        method: 'GET',
        params: { num: e.orderNum },
      }).then((response) => {
        if (response) {
          if (response.success) {
            if (response.result.success) {
              var orderHed = response.result.data;
              if (orderHed.orderDate) orderHed.orderDate = moment(orderHed.orderDate);
              if (orderHed.requestDate) orderHed.requestDate = moment(orderHed.requestDate);
              this.setState({
                data: orderHed,
                orderDtls: orderHed.items,
                orderRels: orderHed.items[0]?.items,
              });
              this.formRef.current.setFieldsValue({ order: orderHed });
              if (orderHed.items && orderHed.items.length > 0) this.setOrderDtl(orderHed.items[0]);
              this.tabSwitch('1');
            } else {
              message.error(response.result.message);
            }
          } else {
            message.error(response.error.message);
          }
          this.setState({ loading: false });
        }
      });
    }
  };
  openModal = (record: any, layout: string) => {
    this.setState({ visible: true, disabled: true, record, layout });
  };
  closeModal = () => {
    this.setState({ visible: false });
  };
  setCurrent = (part?: any) => {
    if (part) {
      var orderDtl: any = {};
      orderDtl.partNum = part.partNum;
      orderDtl.lineDesc = part.partDescription;
      orderDtl.ium = part.ium;
      this.formRef.current.setFieldsValue({ orderDtl });
      this.setState({ partRevs: part.revs });
    }
  };
  setOrderDtl = (orderDtl: any) => {
    if (orderDtl.requestDate) orderDtl.requestDate = moment(orderDtl.requestDate);
    if (orderDtl.warrantyDate) orderDtl.warrantyDate = moment(orderDtl.warrantyDate);
    if (orderDtl.qsDate) orderDtl.qsDate = moment(orderDtl.qsDate);
    this.formRef.current.setFieldsValue({ orderDtl });
    if (orderDtl.items && orderDtl.items.length > 0) this.setOrderRel(orderDtl.items[0]);
    this.setState({ orderRels: orderDtl.items, orderDtl, defTab: '2' });
  };
  setOrderRel = (orderRel: any) => {
    if (orderRel.requestDate) orderRel.requestDate = moment(orderRel.requestDate);
    this.formRef.current.setFieldsValue({ orderRel });
    this.setState({ orderRel, defTab: '3' });
  };
  tabSwitch = (key: any) => {
    this.setState({ defTab: key });
  };
  onSelectChange = (selectedRowKeys: any) => {
    this.setState({ selectedRowKeys });
  };
  onSelectChange2 = (selectedRowKeys2: any) => {
    this.setState({ selectedRowKeys2 });
  };
  render() {
    const { data, defTab, selectedRowKeys, selectedRowKeys2, orderErr, orderDtlErr, orderRelErr, loading } = this.state;
    const layout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const columns = [
      {
        title: '分录',
        dataIndex: 'orderLine',
        key: 'orderLine',
        width: 60
      },
      {
        title: '未结',
        dataIndex: 'openLine',
        key: 'openLine',
        render: (text: boolean) => <Checkbox checked={text} />,
        width: 60
      },
      {
        title: '产品',
        dataIndex: 'partNum',
        key: 'partNum',
      },
      {
        title: '产品描述',
        dataIndex: 'lineDesc',
        key: 'lineDesc',
        ellipsis: true,
      },
      {
        title: '销售数量',
        dataIndex: 'orderQty',
        key: 'orderQty',
      },
      {
        title: '单价',
        dataIndex: 'unitPrice',
        key: 'unitPrice',
      },
    ];
    const columnRel = [
      {
        title: '分录',
        dataIndex: 'orderLine',
        key: 'orderLine',
        width: 60
      },
      {
        title: '项目',
        dataIndex: 'orderRelNum',
        key: 'orderRelNum',
        width: 60
      },
      {
        title: '订单数量',
        dataIndex: 'ourReqQty',
        key: 'ourReqQty',
      },
      {
        title: '未结',
        dataIndex: 'openRelease',
        key: 'openRelease',
        render: (text: boolean) => <Checkbox checked={text} />,
      },
      {
        title: '需求日',
        dataIndex: 'requestDate',
        key: 'requestDate',
        render: (text: any) => <span>{moment(text).format('YYYY-MM-DD')}</span>,
      },
      {
        title: '直接生产',
        dataIndex: 'make',
        key: 'make',
        render: (text: boolean) => <Checkbox checked={text} />,
      },
      {
        title: '直接采购',
        dataIndex: 'buyToOrder',
        key: 'buyToOrder',
        render: (text: boolean) => <Checkbox checked={text} />,
      },
    ];
    const selectRev = (
      <Select placeholder="选择版本">
        {this.state.partRevs?.map((item: any) => {
          return (
            <Select.Option key={item} value={item}>
              {item}
            </Select.Option>
          );
        })}
      </Select>
    );
    const optionCust = this.state.optionCust?.map((d: any) => {
      return (
        <Select.Option value={d.custNum} key={d.id}>
          {d.customerName}
        </Select.Option>
      );
    });
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const rowSelection2 = {
      selectedRowKeys2,
      onChange: this.onSelectChange2,
    };
    const disabled = data == null || data.orderNum == 0
    return (
      <PageHeaderWrapper>
        <Form {...layout} ref={this.formRef} onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}>
          <Space style={{ marginBottom: 8 }}>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => this.newObj()}>
              新增
            </Button>
            <Button type="primary" htmlType="submit" loading={loading} disabled={disabled}>
              保存
            </Button>
            <Button type="primary" icon={<SyncOutlined />} onClick={() => this.getObj(data)}>
              刷新
            </Button>
            <Button
              danger
              icon={<CloseOutlined />}
              disabled={disabled}
              onClick={this.delObj}
            >
              删除
            </Button>
            <DocHelper page="gncidv" />
          </Space>
          <Row gutter={16}>
            <Col xs={24} sm={24} md={24} lg={10} xl={10}>
              <Card>
                <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={this.tabSwitch}>
                  <TabPane tab={<Badge count={orderErr}>汇总</Badge>} key="1">
                    <Form.Item wrapperCol={{ offset: 5 }} style={{ marginBottom: 0 }}>
                      <Input.Group compact>
                        <Form.Item name={['order', 'openOrder']} valuePropName="checked">
                          <Checkbox>未结</Checkbox>
                        </Form.Item>
                        <Form.Item name={['order', 'approve']} valuePropName="checked">
                          <Checkbox>核准</Checkbox>
                        </Form.Item>
                        <Form.Item name={['order', 'voidOrder']} valuePropName="checked">
                          <Checkbox>无效</Checkbox>
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>
                    <Form.Item name={['order', 'id']} label="ID" hidden>
                      <Input />
                    </Form.Item>
                    <Form.Item label="订单号">
                      <Input.Group compact>
                        <SoSelect
                          width={180}
                          noStyle
                          name={['order', 'orderNum']}
                          rules={[{ required: true, message: '请输入订单号' }]}
                          setCurrent={this.getObj}
                        />
                      </Input.Group>
                    </Form.Item>
                    <Form.Item name={['order', 'custNum']} label="选择客户">
                      <Select
                        style={{ width: 240 }}
                        showSearch
                        placeholder="请选择客户"
                        filterOption={(input, option: any) =>
                          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                      >
                        {optionCust}
                      </Select>
                    </Form.Item>
                    <CateComp
                      layout="Currency"
                      width={200}
                      name={['order', 'currencyCode']}
                      label="货币类型"
                    />
                    <CateComp
                      layout="ShipVia"
                      width={200}
                      name={['order', 'shipViaCode']}
                      label="运输方法"
                    />
                    <Form.Item
                      name={['order', 'orderDate']}
                      label="订单日期"
                      rules={[{ required: true, message: '请选择到期日' }]}
                    >
                      <DatePicker />
                    </Form.Item>
                    <Form.Item
                      name={['order', 'requestDate']}
                      label="需求日期"
                      rules={[{ required: true, message: '请选择需求日期' }]}
                    >
                      <DatePicker />
                    </Form.Item>

                    <Form.Item
                      name={['order', 'contactor']}
                      label="联系人"
                      rules={[{ required: true, message: '请输入联系人' }]}
                    >
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item
                      name={['order', 'phoneNum']}
                      label="联系电话"
                      rules={[{ required: true, message: '请输入电子邮件' }]}>
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                  </TabPane>
                  <TabPane tab={<Badge count={orderDtlErr}>分录明细</Badge>} key="2">
                    <Form.Item name={['orderDtl', 'id']} hidden={true}>
                      <Input />
                    </Form.Item>
                    <Form.Item label="分录" style={{ marginBottom: 0 }}>
                      <Input.Group compact>
                        <Form.Item name={['orderDtl', 'orderLine']}>
                          <InputNumber disabled />
                        </Form.Item>
                        <Form.Item name={['orderDtl', 'openLine']} valuePropName="checked">
                          <Checkbox>未结</Checkbox>
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>
                    <Form.Item label="产品编码" style={{ marginBottom: 0 }}>
                      <Input.Group compact>
                        <PartSelect
                          name={['orderDtl', 'partNum']}
                          width={200}
                          required={true}
                          placeholder="产品编码"
                          setCurrent={this.setCurrent}
                          pType="M"
                        />

                        <Form.Item
                          name={['orderDtl', 'revisionNum']}
                        >
                          {selectRev}
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>

                    <Form.Item name={['orderDtl', 'lineDesc']} label="产品描述">
                      <Input.TextArea readOnly disabled />
                    </Form.Item>
                    <Form.Item
                      name={['orderDtl', 'unitPrice']}
                      label="单价"
                      rules={[{ required: true, message: '请输入单价' }]}
                    >
                      <Input prefix="￥" suffix="RMB" style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item label="数量" style={{ marginBottom: 0 }}>
                      <Input.Group compact>
                        <Form.Item name={['orderDtl', 'orderQty']}>
                          <InputNumber min={0} />
                        </Form.Item>
                        <Form.Item name={['orderDtl', 'ium']}>
                          <Input placeholder="单位" style={{ width: 60 }} disabled />
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>
                    <Form.Item name={['orderDtl', 'discount']} label="折扣">
                      <Input suffix="%" style={{ width: 100 }} />
                    </Form.Item>
                    <Form.Item
                      name={['orderDtl', 'requestDate']}
                      label="需求日期"
                      rules={[{ required: true, message: '请选择需求日期' }]}
                    >
                      <DatePicker />
                    </Form.Item>
                    <Form.Item
                      name={['orderDtl', 'warrantyDate']}
                      label="保修期"
                    >
                      <DatePicker />
                    </Form.Item>
                    <Form.Item
                      name={['orderDtl', 'qsDate']}
                      label="质保期"
                    >
                      <DatePicker />
                    </Form.Item>
                  </TabPane>
                  <TabPane tab={<Badge count={orderRelErr}>发货明细</Badge>} key="3">
                    <Form.Item name={['orderRel', 'id']} hidden={true}>
                      <Input />
                    </Form.Item>
                    <Form.Item label="发货行" name={['orderRel', 'orderRelNum']}>
                      <InputNumber disabled />
                    </Form.Item>
                    <Form.Item
                      name={['orderRel', 'ourReqQty']}
                      label="订单数量"
                    >
                      <InputNumber min={1} />
                    </Form.Item>
                    <Form.Item
                      name={['orderRel', 'requestDate']}
                      label="需求日期"
                    >
                      <DatePicker />
                    </Form.Item>
                    <CateComp
                      layout="ShipVia"
                      width={200}
                      name={['orderRel', 'shipViaCode']}
                      label="运输方法"
                    />
                    <Form.Item wrapperCol={{ offset: 5 }} style={{ marginBottom: '0px' }}>
                      <Input.Group compact>
                        <Form.Item name={['orderRel', 'openRelease']} valuePropName="checked">
                          <Checkbox>未结</Checkbox>
                        </Form.Item>
                        <Form.Item name={['orderRel', 'buyToOrder']} valuePropName="checked">
                          <Checkbox>直接采购</Checkbox>
                        </Form.Item>
                        <Form.Item name={['orderRel', 'dropShip']} valuePropName="checked">
                          <Checkbox>直接出货</Checkbox>
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>
                  </TabPane>
                  <TabPane tab="其它信息" key="4">
                    <Form.Item name={['order', 'projectNum']} label="项目号">
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item name={['order', 'poNum']} label="客户PO号">
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item name={['order', 'userChar1']} label="终端客户">
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item
                      name={['order', 'emailAddress']}
                      label="电子邮件">
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item name={['order', 'address']} label="联系地址">
                      <Input.TextArea />
                    </Form.Item>
                  </TabPane>
                  <TabPane tab="订单备注" key="5">
                    <Form.Item name={['order', 'orderComment']}>
                      <Input.TextArea rows={10} />
                    </Form.Item>
                  </TabPane>
                </Tabs>
              </Card>
            </Col>
            <Col xs={24} sm={24} md={24} lg={14} xl={14}>
              <Card>
                <Tabs defaultActiveKey="1">
                  <TabPane tab="分录项" key="1">
                    <Table
                      rowKey="id"
                      size="small"
                      columns={columns}
                      dataSource={this.state.orderDtls}
                      onRow={(record) => {
                        return {
                          onClick: (event) => {
                            this.setOrderDtl(record);
                          },
                        };
                      }}
                      rowSelection={rowSelection}
                    />
                    <Row gutter={16}>
                      <Col span={12}>
                        <Button block type="dashed" icon={<PlusOutlined />} onClick={this.newDtl}>
                          添加分录
                        </Button>
                      </Col>
                      <Col span={12}>
                        <Button block danger icon={<CloseOutlined />} onClick={this.delDtl}>
                          删除分录
                        </Button>
                      </Col>
                    </Row>
                  </TabPane>
                  <TabPane tab="发货行" key="2">
                    <Table
                      rowKey="id"
                      size="small"
                      columns={columnRel}
                      dataSource={this.state.orderRels}
                      onRow={(record) => {
                        return {
                          onClick: (event) => {
                            this.setOrderRel(record);
                          },
                        };
                      }}
                      rowSelection={rowSelection2}
                    />
                    <Row gutter={16}>
                      <Col span={12}>
                        <Button block type="dashed" icon={<PlusOutlined />} onClick={this.newRel}>
                          添加发货项
                        </Button>
                      </Col>
                      <Col span={12}>
                        <Button block danger icon={<CloseOutlined />} onClick={this.delRel}>
                          删除发货项
                        </Button>
                      </Col>
                    </Row>
                  </TabPane>
                </Tabs>
              </Card>
            </Col>
          </Row>
        </Form>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
